import host from '../config'
const request = (e) => {
  return new Promise((resolve, reason) => {
    wx.request({
      url: host.url + e.url,
      data: e.data ? e.data : {},
      dataType: e.dataType ? e.dataType : {},
      enableCache: true,
      enableHttp2: true,
      enableQuic: true,
      header: {
        'Cookie': wx.getStorageSync('tokens') || '',
      },
      method: e.method ? e.method : 'get',
      responseType: e.responseType ? e.responseType : '',
      timeout: e.timeout ? e.timeout : 0,
      success: (result) => {
        var res = JSON.parse(result.data);
        if (e.url == 'mini/login') {
              console.log(result.cookies,'result')
              let token = result.cookies[0].split(';')[0]
              console.log(token)
              wx.setStorageSync('tokens', token);  //保存Cookie到Storage
        }
        if(res.code == 401){
          wx.showModal({
            title: '提示',
            content: '您还未登录，是否进行登录',
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/login/login',
                })
                wx.hideLoading()
              } else if (res.cancel) {
               wx.hideLoading()
              }
            }
          })
        }
        resolve(res)
      },
      fail: e.fail ? e.fail : (res) => {
        wx.showToast({
          title: '出现错误啦，请稍后再试',
          icon: 'none'
        })
        reason(JSON.parse(res.data))
      },
      complete: e.complete ? e.complete : (res) => {
        reason(JSON.parse(res.data));
      },
    })
  })
}
const uploadFile = (e)=>{
  console.log(e,'formData')
  return new Promise((resolve, reason) => {
    wx.uploadFile({
      url: host.url+ e.url, //仅为示例，非真实的接口地址
      filePath: e.filePath,
      name: 'image',
      formData: {
        type:e.type
      },
      header:{
        'Cookie': wx.getStorageSync('tokens') || '',
      },
      success (res){
        resolve(res)
      },
      fail:e=>{
        reason(e)
      }
    })
  })
}

module.exports = {
  request: request,
  uploadFile:uploadFile
}